<template>
	<om-page ref="page" :title="menuName">
		<view class="om-addpage_choose_btn" :style="[{top: getHistoryTop}]">
			<button v-if="showChooseBtn" size="mini" class="om-history-btn" @click="chooseFunc" style="height: 32px;line-height: 32px;">选单</button>
		</view>
		<view class="om-addpage_history_btn" :style="[{top: getHistoryTop}]">
			<button v-if="showHistoryBtn" size="mini" class="om-history-btn" @click="recordFunc" style="height: 32px;line-height: 32px;">历史记录</button>
		</view>
		<view class="page__bd om-addpage_body">
			<om-wing-blank size="default">
				<form @submit="formSubmit" @reset="formReset">
					<slot></slot>
					<view class="tui-col-12 margin-top-xs flex" v-show="delayShow">
						<button v-if="resetBtnText" class="bg-grey" :style="{'width':(saveBtnText?'50%':'100%'),'margin-left':(saveBtnText?'1%':'0')}" form-type="reset">{{resetBtnText}}</button>
						<button v-if="saveBtnText" class="text-white om-btn-color" :style="{'width':(resetBtnText?'50%':'100%'),'margin-left':(resetBtnText?'1%':'0')}" form-type="submit">{{saveBtnText}}</button>
						<slot name="form-footer"></slot>				
					</view>
				</form>
			</om-wing-blank>
		</view>
		<tui-scroll-top :scrollTop="scrollTop" style="background: rgba(124, 174, 255, 0.5);"></tui-scroll-top>
		<uni-popup  id="popup" ref="popup" :type="'center'">
			<view class="popup-cotent padding">
				<view class="margin popup-tip">
					请选择表单
				</view>
				<view  class="popup-item padding"  v-for="(item,index) of menuList" :key="index" @click="toShow(item)">
					<text >
						{{item.text}}
					</text>
					<uni-icons :size="20" class="uni-icon-wrapper" color="#bbb" type="arrowright" />
				</view>
				<view class="margin flex justify-end" @click="cancel">
					<text class="margin-top om-color">
						取消
					</text>
				</view>
			</view>
		</uni-popup>
	</om-page>
</template>

<script>
	import {
		formValidation,
		setSubmitSubValue
	} from '../../../static/js/formUtil.js';
	export default {
		props: {
			menuName: {
				type: String,
				default () {
					return '';
				}
			},
			showChooseBtn:{
				type: Boolean,
				default () {
					return false;
				}
			},
			busCode: {
				type: String,
				default () {
					return '';
				}
			},
			scrollTop: {
				type: Number,
				default () {
					return 0;
				}
			},
			showHistoryBtn: {
				type: Boolean,
				default () {
					return true;
				}
			},
			saveBtnText: {
				type: String,
				default () {
					return '保存';
				}
			},
			resetBtnText: {
				type: String,
				default () {
					return '';
				}
			},
			//历史记录按钮离上边线距离，px
			historyBtnTop: {
				type: [Number, String],
				default () {
					return '';
				}
			},
			customAddFunc: {
				type: Boolean,
				default () {
					return false;
				}
			},
			customDelFunc: {
				type: Boolean,
				default () {
					return false;
				}
			},
			menuList:{
				type: Array,
				default () {
					return [];
				}
			}
		},
		inject: ['formPage'],
		data() {
			return {
				//上传文件参数
				interval: null,
				valTimes: 0,
				addTimes: 0,
				deleteTimes: 0,
				delayShow: false
			}
		},
		mounted() {
		    setTimeout(() => {
		        this.delayShow = true
		    }, 2000);
		  },
		computed: {
			getCustomBar() {
				// #ifdef H5 || APP-PLUS
				return '10px'
				// #endif
				// #ifdef MP-WEIXIN
				return this.CustomBar + 10 + 'px'
				// #endif
			},
			getHistoryTop() {
				var top = this.historyBtnTop,
					result = this.getCustomBar;
				if (top) {
					if (top.endsWith("px")) {
						result = top
					} else {
						result = top + 'px'
					}
				}
				return result
			}
		},
		methods: {
			toShow(item){
				let _that = this
				uni.navigateTo({
					url:'/pages/public/chooseOtherForm/chooseOtherForm',
					success:(res)=>{
						res.eventChannel.emit('getCodes', {
							leftFormCode:_that.busCode, 
							rightFormCode:item.code,
						})
					}
				})
				_that.$refs.popup.close()
			},
			cancel(){
				let _that = this
				_that.$refs.popup.close()
			},
			chooseFunc(){
				let _that = this
				_that.$refs.popup.open()
			},
			initParam() {
				let _that = this
				this.interval = null
				this.valTimes = 0
				this.addTimes = 0
				this.deleteTimes = 0
			},
			/**
			 * 历史记录
			 */
			recordFunc(e) {
				if (this.menuName && this.busCode) {
					this.om.openHistoryPage(this.menuName, this.busCode)
				}
			},
			formSubmit(e) {
				if (this.customAddFunc) {
					this.$emit("formSubmit")
				} else {
					if (!this.formPage.$refs.autoform) {
						this.$emit("formSubmit")
					} else {
						//确认前验证
						if (this.formPage.verifySubConfirm) {
							var ret = this.formPage.verifySubConfirm()
							if (typeof(ret) == "boolean") {
								if (!ret) {
									return
								}
							} else if (typeof(ret) == "string") {
								this.om.toast(ret)
								return
							}
						}
						this.initParam()
						let _that = this
						setSubmitSubValue();
						var checkRes = formValidation(_that.formPage.$refs.autoform.configData, _that.formPage.formdata)
						if (!checkRes) {
							var fileEditors = _that.formPage.$refs.autoform.getFileEditor()
							if (fileEditors.length == 1) {
								var editor = fileEditors[0]
								if (editor.type === "imagebox") {
									//提交文件集合先初始化为空数组
									_that.formPage.$refs.autoform.formdata[editor.valueField] = []
									var keepFiles = [],
										addFiles = [],
										delFiles = [];
									if (editor.tempFileList.length) {
										for (var i = 0; i < editor.tempFileList.length; i++) {
											var o = editor.tempFileList[i]
											if (editor.fileUrlList.includes(o)) {
												keepFiles.push(o)
											} else {
												addFiles.push(o)
											}
										}
										delFiles = editor.fileUrlList.filter(e => !keepFiles.includes(e));
									} else {
										delFiles = editor.fileUrlList
									}
									if (delFiles) {
										_that.DelImges(delFiles, 0, editor)
									}
									if (keepFiles) {
										editor.fileUrlList = []
										for (let item of _that.formPage.formdata[editor.valueField]) {
											if (keepFiles.includes(item.fileSaveName)) {
												editor.fileUrlList.push(item.fileSaveName)
												let obj = {
													fileSaveName: item.fileSaveName,
													fileName: item.fileName,
													id: item.id
												}
												_that.formPage.$refs.autoform.formdata[editor.valueField].push(obj)
											}
										}
									}
									if (addFiles) {
										_that.uploadImg(addFiles, 0, editor)
									}
									_that.interval = setInterval(function() {
										uni.showLoading({
											mask: true,
											title: '请稍候...'
										})
										_that.valTimes++
										if (_that.interval && (_that.valTimes > 40 || (_that.addTimes + _that.deleteTimes) == (addFiles.length +
												delFiles.length))) {
											uni.hideLoading()
											clearInterval(_that.interval);
											_that.$emit('formSubmit', e.detail.value)
										}
									}, 250)
								}else{
									delete _that.formPage.formdata.bottomFileList
									delete _that.formPage.formdata.bottomFileUpload
									_that.$emit('formSubmit', e.detail.value)
								}
							} else if (fileEditors.length > 1) {
								_that.om.toast("有多个文件上传组件，请使用自定义上传方法")
								return
							} else {
								_that.$emit('formSubmit', e.detail.value)
							}
						} else {
							_that.om.toast(checkRes);
						}
					}
				}

			},
			formReset(e) {
				this.$emit('formReset')
			},
			uploadImg(tempFilePaths, i, editor) {
				let _that = this
				if (tempFilePaths && tempFilePaths.length > i) {
					var filePath = tempFilePaths[i]
					_that.om.uploadFile(_that.getUploadUrl(editor), filePath, null, {
						key: editor.fileUploadKey
					}).then(d => {
						_that.addTimes++
						var json = JSON.parse(d)
						if (json.succeed) {
							if (json.value) {
								editor.fileUrlList.push(json.value.saveName)

								var obj = {}
								obj[_that.getFileNameField(editor)] = json.value.uploadName
								obj[_that.getFileSaveNameField(editor)] = json.value.saveName

								_that.formPage.$refs.autoform.formdata[editor.valueField].push(obj)
								if (editor.nameField) {
									_that.formPage.$refs.autoform.formdata[editor.nameField] = JSON.stringify(_that.formPage.$refs.autoform.formdata[
										editor.valueField])
								} else {
									_that.om.toast("上传失败，未定义文件上传参数")
									return
								}
							} else {
								_that.om.toast("上传失败，请重新上传")
								return
							}
						} else {
							_that.om.toast(json.msg)
							return
						}
						i++
						_that.uploadImg(tempFilePaths, i, editor)
					})
				}
			},
			DelImges(deleteFiles, i, editor) {
				if (!i) {
					i = 0
				}
				let _that = this
				if (deleteFiles && deleteFiles.length > i) {
					let index = null
					let file = _that._.find(_that.formPage.formdata[editor.valueField], function(e, ind) {
						index = ind
						return e[_that.getFileSaveNameField(editor)] == deleteFiles[i]
					})
					if (!file) {
						return
					}
					_that.om.request(_that.getRemoveUrl(editor), {
						fileName: file[_that.getFileSaveNameField(editor)],
						key: editor.fileUploadKey
					}, 'post').then(res => {
						_that.deleteTimes++
						if (res.succeed) {
							for (let item of _that.formPage.$refs.autoform.formdata[editor.valueField]) {
								if (!item.hasOwnProperty('id')) {
									_that.formPage.$refs.autoform.formdata[editor.valueField].splice(index, 1)
								}
							}

						}
						i++
						_that.DelImges(deleteFiles, i, editor)
					})
				}
			},
			getFileSaveNameField(editor) {
				return editor.fileSaveNameField || "fileSaveName"
			},
			getFileNameField(editor) {
				return editor.fileNameField || "fileName"
			},
			getUploadUrl(editor) {
				return editor.uploadUrl || "uploadFileData/uploadInterimFile"
			},
			getRemoveUrl(editor) {
				return editor.removeUrl || "uploadFileData/removeInterimFile"
			}
		}
	}
</script>

<style>
	.om-addpage_history_btn {
		position: absolute;
		width: 25%;
		right: 5px;
		z-index: 10;
	}
    .om-addpage_choose_btn {
		position: absolute;
		width: 25%;
		left: 5px;
		z-index: 10;
	}

	.om-addpage_body {
		margin-top: 10px;
	}
</style>
